package com.example.demo3.controller;


import com.example.demo3.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    //用于访问数据库的组件
    @Autowired
    JdbcTemplate jdbcTemplate;

    @RequestMapping("users")
    public Object userList() {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from user");
//        List<Map<String, Object>> list =  jdbcTemplate.queryForList("select * from user");
        List<User> list2 = jdbcTemplate.query("select * from user ", new BeanPropertyRowMapper(User.class));
//        User u = list.get(0);
        return list2;
    }

    @RequestMapping("user")
    public Object user() {
//        List<Map<String, Object>> list =  jdbcTemplate.queryForList("select * from user");
        User user = jdbcTemplate.queryForObject("select * from user where id=1 ", new BeanPropertyRowMapper<>(User.class));
        return user;
    }

    @RequestMapping("add")
    public Object add() {
        String sql = "INSERT INTO user(id,name)  VALUES (null, ?) ";
        int succ = jdbcTemplate.update(sql, "李四");
        return succ;
    }

    @RequestMapping("del")
    public Object del() {
        String sql = "DELETE from user where id = ? ";
        int succ = jdbcTemplate.update(sql, 12);
        return succ;
    }


}

